package org.openmrs.web.controller.user;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openmrs.Attribute;
import org.openmrs.AttributeAssignment;
import org.openmrs.AttributeInformation;
import org.openmrs.AttributeValue;
import org.openmrs.User;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public class AttributeListController extends SimpleFormController {
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
		binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true));
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
	        BindException errors) throws Exception {
		String view = getFormView();
		return new ModelAndView(new RedirectView(view));
	}
	
	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
		
		//map containing the privilege and true/false whether the privilege is core or not
		List<AttributeInformation> attributeInfoList = new ArrayList<AttributeInformation>();
		
		if (Context.isAuthenticated()) {
			UserService us = Context.getUserService();
			
			List<Attribute> attributeList = us.getAllAttributes();
			
			for (Attribute attribute : attributeList) {
				List<AttributeAssignment> attribAssignmentList = us.getAllAssignmentsByAttribute(attribute);
				
				for (AttributeAssignment attribAssingment : attribAssignmentList) {
					User assignedUser = attribAssingment.getUser();
					
					List<AttributeValue> attribValueList = us.getAttributeValuesByUserAttribute(assignedUser, attribute);
					
					for (AttributeValue attribValue : attribValueList) {
						AttributeInformation attribInfo = new AttributeInformation();
						attribInfo.setName(attribute.getAttributeName());
						attribInfo.setDataType(attribute.getDataType());
						attribInfo.setType(attribute.getOwnerType());
						attribInfo.setUserName(assignedUser.getUsername());
						attribInfo.setCurrentValue(attribValue.getAttributeValue());
						
						attributeInfoList.add(attribInfo);
						
					}
				}
			}
		}
		
		request.setAttribute("attribInfo", attributeInfoList);
		//only fill the Object is the user has authenticated properly
		return attributeInfoList;
	}
	
}
